﻿using Mapster;
using Zhp.Common.WebApp;
using Zhp.Entity.Chat;
using Zhp.IService.Chat;
using Zhp.Model.Chat;
using Zhp.Service.Base;
using Zhp.SqlSugar.Repository;

namespace Zhp.Service.Chat
{
    public class ChatMessageReadService : BaseService<ChatMessageRead>, IChatMessageReadService
    {
        IBaseRepository<ChatMessage> _chatMessageRep;
        public ChatMessageReadService(ICurrentUser currentUser, IBaseRepository<ChatMessageRead> rep, IBaseRepository<ChatMessage> chatMessageRep)
        {
            _currentUser = currentUser;
            _rep = rep;
            _chatMessageRep = chatMessageRep;
        }

        /// <summary>
        /// 查询当前用户未读消息
        /// </summary>
        /// <returns></returns>
        public async Task<List<ChatMessageModel>> GetChatMessageNoReadList()
        {
            var noReadList = await _rep.GetListAsync(x => x.UserId == _currentUser.UserId && x.ReadTime == null);

            var list = await _chatMessageRep.GetListAsync(x => noReadList.Select(x => x.MsgId).Contains(x.Id));

            return list.Adapt<List<ChatMessageModel>>();
        }

        /// <summary>
        /// 未读消息标记为已读
        /// </summary>
        /// <param name="msgId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<bool> UpdateMsgReaded(long msgId, long userId)
        {
            var msg = await _rep.GetFirstAsync(x => x.MsgId == msgId && x.UserId == userId);
            if (msg != null)
            {
                msg.ReadTime = DateTime.Now;
                return await _rep.UpdateAsync(msg);
            }

            return true;
        }

        /// <summary>
        /// 创建未读消息记录
        /// </summary>
        /// <param name="msgId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<bool> Create(long msgId, long userId)
        {
            var msg = new ChatMessageRead
            {
                MsgId = msgId,
                UserId = userId,
            };

            return await _rep.InsertAsync(msg);
        }
    }
}
